/**
 * Created with CLion.
 * Description: 
 * User: loong
 * Date: 2024/6/12
 * Time: 12:24
 */

#include "Game.h"

#include "Card.h"
#include "CardDeck.h"
namespace Upgrade {
    Game::Game(int _playerNum, int _deckNum, int bottomNum)
        : deck_(make_shared<CardDeck>(_deckNum, bottomNum))
        , timer_(new QTimer)
    {
        timer_->setInterval(10s);
        InitEvent();
    }

    void Game::InitEvent()
    {
        connect(timer_,&QTimer::timeout,this,[=]() {
            emit TimeOut();
           // 超时：检测是否有主 没有定为公主，用户选择第一个用户
            qDebug() <<  "No player select! Default!";
            SetMainSuit(nullptr == main_player_ ? players_.first() : main_player_,CardSuit::JokerSuit);
       });
    }
    void Game::AddPlayer(PlayerSPtr _player)
    {
        players_.push_back(_player);
        player_trump_.insert(_player->Group(), CardRank::Two);
    }

    void Game::Upgrade(bool isMain, int rank)
    {
        //TODO 升级暂不按分数
        // if(isMain)
        //     a_rank = static_cast<CardRank>(rank + static_cast<int>(a_rank));
        // else
        //     b_rank = static_cast<CardRank>(rank + static_cast<int>(b_rank));
    }

    void Game::Start()
    {
        deck_->Shuffle();

        // 发牌
        int index = 0;
        while(auto card = deck_->Deal()) {
            auto player = players_[index++ % players_.size()];
            qApp->processEvents();

            player->ReceiveCard(card);
            emit SendCard(player, card);
        }
        // 发牌结束(有底牌)
        emit DealFinished(main_player_);
        timer_->start();
    }

    void Game::PrintBottomCard()
    {
        deck_->Print();
    }

    void Game::SetMainSuit(const PlayerSPtr & _player, CardSuit _suit)
    {
        QMutexLocker locker(&mutex_);
        main_player_ = _player;
        main_suit_   = _suit;

        qDebug() << "Game Setting trump:" << _player->Name() << "\t" <<  _suit ;

        emit IsAlready(main_player_, main_suit_);
        if(timer_->isActive())
            timer_->stop();
    }

    PlayerSPtr Game::GetMainPlayer()
    {
        QMutexLocker locker(&mutex_);
        return main_player_;
    }

    CardSuit Game::GetMainSuit() const
    {
        QMutexLocker locker(&mutex_);
        return main_suit_;
    }

    CardRank Game::GetMainRank() const
    {
        return nullptr == main_player_ ? CardRank::Two : player_trump_.value(main_player_->Group());
    }

} // Upgrade